import os.path
import gc
import sys
import shutil

from configs import *
import os
import random
import re

class SandBox(object):
    """
    # TODO docu for sandbox
    """
    def __init__(self, flag):
        if flag == "new":
            files = os.listdir(os.getcwd())
            for file in files:
                if re.search("creature_.*", file):
                    print "loesche" , file
                    os.remove(os.getcwd() + os.sep + file)
        else:
            # fuer spaeter
            pass

        self.loadables = 0
        # 0 = parentid 
        self.ids =[0]
        # noch nicht benutzt
        self.generation = 0
        self.creatures = []

        self.rootid = self.unique_id()
        shutil.copyfile("creature.py", "creature_0.py")
        root_creature = __import__("creature_0", globals(), locals(), [], -1)
        print "Create First Creature:" , self.rootid
        self.creatures.append(root_creature.Creature(self.rootid, self, 0))

    def start(self):
        """Starts LIVE! :)"""
           
        while True:
            print "Creature Count:" , len(self.creatures)
            for thing in self.creatures:
                try:
                    print "Live:" , thing.id
                    thing.live()
                    if thing.id != self.rootid:
                        print "Child executed!"
                        sys.exit()
                except Exception, e:
                    print "Exception(live):" , sys.exc_type , e
                    if thing.id == self.rootid:
                        continue
                    try:
                        print "Deleting:" , str(thing.id)
                        path = os.getcwd() + os.sep + "creature_" + str(thing.parentid) + ".py"
                        if os.path.exists(path):
                            os.remove(os.getcwd() + os.sep + "creature_" + str(thing.parentid) + ".py")
                            print "Ceature Code:" , thing.parentid , "deleted"
                        path = path.replace(".py", ".pyc")
                        if os.path.exists(path):
                            os.remove(os.getcwd() + os.sep + "creature_" + str(thing.parentid) + ".pyc")
                    except Exception, e:
                        print "Exception(delete): " , sys.exc_type , e
                        sys.exit()
                    self.ids.remove(thing.id)
                    self.creatures.remove(thing)
            if len(self.creatures) == 0:
                print "ENDE"
                sys.exit()

    def unique_id(self):
        """Ensure that the creature id is unique"""
        # TODO andersmachen! evtl id=creature_GEN.ID.py ?
        # TODO CONSTANTE aendern
        id = random.randint(1, CREATURE_COUNT)
        while id in self.ids:
            id = random.randint(1, CREATURE_COUNT)
        self.ids.append(id)
        return id

    def create_creature(self, filename, parentid):
        """Tries to create a new creature with code from filename"""
        try:
            print "Loading:" , filename
            mutated_dns = __import__(filename.rstrip(".py"), globals(), locals(), [], -1)
            id = self.unique_id()
            print "Create:" , id , "with Parentid: " , parentid
            child = mutated_dns.Creature(id=id, sandbox=self, parentid=parentid)
            self.creatures.insert(0, child)
            self.creature_loadable(child)
        except SyntaxError, e:
            print "SyntaxError: " , e
            os.remove(os.getcwd() + os.sep + filename)
        except AttributeError, e:
            print "AttributeError: " , e
            os.remove(os.getcwd() + os.sep + filename)
        except Exception, e:
            print "Exception: " , sys.exc_type , e
            os.remove(os.getcwd() + os.sep + filename)

    def creature_loadable(self, child):
        print "Creature" , child.id , "loaded!"
        self.loadables += 1


if __name__ == "__main__":
    leben = SandBox("new")
    leben.start()